const { executeQuery } = require('../config/dbConfig');

class NotificationService {
  // 获取通知列表
  async getNotifications(userId) {
    const notifications = await executeQuery(
      'SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC',
      [userId]
    );
    return notifications;
  }

  // 获取通知详情
  async getNotificationById(id, userId) {
    const notifications = await executeQuery(
      'SELECT * FROM notifications WHERE id = ? AND user_id = ?',
      [id, userId]
    );

    return notifications[0];
  }

  // 标记单个通知为已读
  async markAsRead(id) {
    await executeQuery(
      'UPDATE notifications SET is_read = 1 WHERE id = ?',
      [id]
    );
    return true;
  }

  // 标记所有为已读
  async markAllAsRead(userId) {
    await executeQuery(
      'UPDATE notifications SET is_read = 1 WHERE user_id = ? AND is_read = 0',
      [userId]
    );
    return true;
  }

  // 删除所有通知
  async deleteAllNotifications(userId) {
    await executeQuery(
      'DELETE FROM notifications WHERE user_id = ?',
      [userId]
    );
    return true;
  }

  // 创建通知
  async createNotification(data) {
    const result = await executeQuery(
      `INSERT INTO notifications (
        user_id, type, title, content, related_id, is_read
      ) VALUES (?, ?, ?, ?, ?, 0)`,
      [
        data.userId,
        data.type,
        data.title,
        data.content,
        data.relatedId || null
      ]
    );
    
    return result.insertId;
  }
}

module.exports = new NotificationService(); 